#include "fileprogressdisplay.h"
#include <QApplication>
#include <QPalette>
#include <QScreen>
#include <QDebug>

FileProgressDisplay::FileProgressDisplay(QWidget* parent)
    : QWidget(parent)
    , m_displayType(Compact)
    , m_isShowing(false)
{
    setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground);

    setupUI();

    // 设置更新定时器
    m_updateTimer = new QTimer(this);
    m_updateTimer->setInterval(UPDATE_INTERVAL_MS);
    connect(m_updateTimer, &QTimer::timeout, this, &FileProgressDisplay::updateDisplay);

    // 设置透明度动画
    m_opacityEffect = new QGraphicsOpacityEffect(this);
    setGraphicsEffect(m_opacityEffect);

    m_fadeAnimation = new QPropertyAnimation(m_opacityEffect, "opacity", this);
    m_fadeAnimation->setDuration(ANIMATION_DURATION_MS);
    connect(m_fadeAnimation, &QPropertyAnimation::finished, this, &FileProgressDisplay::onAnimationFinished);

}

FileProgressDisplay::~FileProgressDisplay()
{
    hideProgress();
}

void FileProgressDisplay::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setSpacing(8);
    m_mainLayout->setContentsMargins(12, 12, 12, 12);

    // 创建所有组件
    setupMinimalUI();
    setupCompactUI();
    setupDetailedUI();

    // 默认设置为紧凑模式
    setDisplayType(Compact);

    // 设置样式
    setStyleSheet(
        "FileProgressDisplay { "
        "    background-color: rgba(248, 248, 248, 240); "
        "    border: 1px solid #ccc; "
        "    border-radius: 8px; "
        "} "
        "QLabel { "
        "    color: #333; "
        "    font-size: 12px; "
        "} "
        "QProgressBar { "
        "    border: 1px solid #bbb; "
        "    border-radius: 4px; "
        "    text-align: center; "
        "    font-size: 11px; "
        "} "
        "QProgressBar::chunk { "
        "    background-color: #4CAF50; "
        "    border-radius: 3px; "
        "} "
        "QPushButton { "
        "    padding: 4px 8px; "
        "    border: 1px solid #bbb; "
        "    border-radius: 4px; "
        "    background-color: white; "
        "    font-size: 11px; "
        "} "
        "QPushButton:hover { "
        "    background-color: #f0f0f0; "
        "} "
        "QPushButton:pressed { "
        "    background-color: #e0e0e0; "
        "}"
    );
}

void FileProgressDisplay::setupMinimalUI()
{
    // 最小化显示组件（用于状态栏）
    // 这些组件将在切换到最小模式时显示
}

void FileProgressDisplay::setupCompactUI()
{
    // 标题标签
    m_titleLabel = new QLabel("处理中...", this);
    m_titleLabel->setStyleSheet("font-weight: bold; font-size: 14px;");
    m_titleLabel->setAlignment(Qt::AlignCenter);
    m_mainLayout->addWidget(m_titleLabel);

    // 文件信息标签
    m_fileInfoLabel = new QLabel("", this);
    m_fileInfoLabel->setAlignment(Qt::AlignCenter);
    m_mainLayout->addWidget(m_fileInfoLabel);

    // 文件进度条
    m_fileProgressBar = new QProgressBar(this);
    m_fileProgressBar->setMinimumHeight(18);
    m_fileProgressBar->setTextVisible(true);
    m_mainLayout->addWidget(m_fileProgressBar);

    // 整体进度条
    m_overallProgressBar = new QProgressBar(this);
    m_overallProgressBar->setMinimumHeight(16);
    m_overallProgressBar->setTextVisible(true);
    m_mainLayout->addWidget(m_overallProgressBar);

    // 状态标签
    m_statusLabel = new QLabel("", this);
    m_statusLabel->setAlignment(Qt::AlignCenter);
    m_statusLabel->setStyleSheet("font-size: 11px; color: #666;");
    m_mainLayout->addWidget(m_statusLabel);
}

void FileProgressDisplay::setupDetailedUI()
{
    // 详细模式的额外组件
    m_timeRemainingLabel = new QLabel("", this);
    m_timeRemainingLabel->setAlignment(Qt::AlignCenter);
    m_timeRemainingLabel->setStyleSheet("font-size: 11px; color: #666;");

    // 按钮布局
    m_buttonLayout = new QHBoxLayout();
    m_buttonLayout->setSpacing(8);

    m_cancelButton = new QPushButton("取消", this);
    m_detailsButton = new QPushButton("详情", this);
    m_minimizeButton = new QPushButton("最小化", this);

    connect(m_cancelButton, &QPushButton::clicked, this, &FileProgressDisplay::onCancelClicked);
    connect(m_detailsButton, &QPushButton::clicked, this, &FileProgressDisplay::onDetailsClicked);
    connect(m_minimizeButton, &QPushButton::clicked, this, &FileProgressDisplay::onMinimizeClicked);

    m_buttonLayout->addStretch();
    m_buttonLayout->addWidget(m_minimizeButton);
    m_buttonLayout->addWidget(m_detailsButton);
    m_buttonLayout->addWidget(m_cancelButton);
    m_buttonLayout->addStretch();
}

void FileProgressDisplay::setDisplayType(DisplayType type)
{
    if (m_displayType == type) return;

    m_displayType = type;
    switchToDisplayType(type);
}

void FileProgressDisplay::switchToDisplayType(DisplayType type)
{
    // 清理现有布局
    while (m_mainLayout->count() > 0) {
        QLayoutItem* item = m_mainLayout->takeAt(0);
        if (item->widget()) {
            item->widget()->setParent(nullptr);
        }
        delete item;
    }

    switch (type) {
    case Minimal:
        setupMinimalLayout();
        setMinimumWidth(MIN_WIDTH_MINIMAL);
        break;

    case Compact:
        setupCompactLayout();
        setMinimumWidth(MIN_WIDTH_COMPACT);
        break;

    case Detailed:
        setupDetailedLayout();
        setMinimumWidth(MIN_WIDTH_DETAILED);
        break;
    }

    adjustSize();
    updateComponentVisibility();
}

void FileProgressDisplay::setupMinimalLayout()
{
    // 最小化布局（适用于状态栏）
    QHBoxLayout* horizontalLayout = new QHBoxLayout();
    horizontalLayout->setContentsMargins(4, 2, 4, 2);

    if (m_fileProgressBar) {
        m_fileProgressBar->setMinimumHeight(18);  // 保持与setupUI()中一致的高度
        horizontalLayout->addWidget(m_fileProgressBar);
    }

    m_mainLayout->addLayout(horizontalLayout);
}

void FileProgressDisplay::setupCompactLayout()
{
    // 紧凑布局
    if (m_titleLabel) m_mainLayout->addWidget(m_titleLabel);
    if (m_fileInfoLabel) m_mainLayout->addWidget(m_fileInfoLabel);
    if (m_fileProgressBar) m_mainLayout->addWidget(m_fileProgressBar);
    if (m_overallProgressBar) m_mainLayout->addWidget(m_overallProgressBar);
    if (m_statusLabel) m_mainLayout->addWidget(m_statusLabel);
}

void FileProgressDisplay::setupDetailedLayout()
{
    // 详细布局
    setupCompactLayout();

    if (m_timeRemainingLabel) m_mainLayout->addWidget(m_timeRemainingLabel);
    if (m_buttonLayout) m_mainLayout->addLayout(m_buttonLayout);
}

void FileProgressDisplay::updateComponentVisibility()
{
    bool isDetailed = (m_displayType == Detailed);

    if (m_timeRemainingLabel) m_timeRemainingLabel->setVisible(isDetailed);
    if (m_cancelButton) m_cancelButton->setVisible(isDetailed && m_progressData.showCancel);
    if (m_detailsButton) m_detailsButton->setVisible(false); // 当前已是详细模式
    if (m_minimizeButton) m_minimizeButton->setVisible(isDetailed);
}

void FileProgressDisplay::showProgress(const QString& title, DisplayType type)
{
    m_currentTitle = title;
    setDisplayType(type);

    if (m_titleLabel) {
        m_titleLabel->setText(title);
    }

    // 居中显示
    if (parentWidget()) {
        QRect parentRect = parentWidget()->geometry();
        move(parentRect.center() - rect().center());
    } else {
        QScreen* screen = QApplication::primaryScreen();
        QRect screenGeometry = screen->geometry();
        move(screenGeometry.center() - rect().center());
    }

    showWithAnimation();
    m_updateTimer->start();

}

void FileProgressDisplay::hideProgress()
{
    if (m_isShowing) {
        hideWithAnimation();
        m_updateTimer->stop();
    }
}

void FileProgressDisplay::showWithAnimation()
{
    if (m_isShowing) return;

    m_isShowing = true;
    show();

    m_fadeAnimation->stop();
    m_fadeAnimation->setStartValue(0.0);
    m_fadeAnimation->setEndValue(1.0);
    m_fadeAnimation->start();
}

void FileProgressDisplay::hideWithAnimation()
{
    if (!m_isShowing) return;

    m_fadeAnimation->stop();
    m_fadeAnimation->setStartValue(1.0);
    m_fadeAnimation->setEndValue(0.0);
    m_fadeAnimation->start();
}

void FileProgressDisplay::onAnimationFinished()
{
    if (m_fadeAnimation->endValue().toDouble() == 0.0) {
        // 淡出动画完成
        m_isShowing = false;
        hide();
    }
}

void FileProgressDisplay::updateFileProgress(const QString& fileName, int currentPage, int totalPages,
                                           FileStatusIconManager::FileStatus status)
{
    m_progressData.currentFileName = fileName;
    m_progressData.currentPage = currentPage;
    m_progressData.totalPages = totalPages;
    m_progressData.status = status;

    updateDisplay();
}

void FileProgressDisplay::updateOverallProgress(int completedFiles, int totalFiles, const QString& operation)
{
    m_progressData.completedFiles = completedFiles;
    m_progressData.totalFiles = totalFiles;
    m_progressData.operation = operation;

    updateDisplay();
}

void FileProgressDisplay::setEstimatedTimeRemaining(int seconds)
{
    m_progressData.estimatedTimeSeconds = seconds;
    updateDisplay();
}

void FileProgressDisplay::setProgress(int current, int total)
{
    if (m_fileProgressBar) {
        m_fileProgressBar->setMaximum(total);
        m_fileProgressBar->setValue(current);
    }
}

void FileProgressDisplay::setStatusText(const QString& text)
{
    m_progressData.statusText = text;
    updateDisplay();
}

void FileProgressDisplay::setShowCancelButton(bool show)
{
    m_progressData.showCancel = show;
    updateComponentVisibility();
}

void FileProgressDisplay::updateDisplay()
{
    if (!m_isShowing) return;

    // 更新文件信息
    if (m_fileInfoLabel && !m_progressData.currentFileName.isEmpty()) {
        QString fileInfo = formatFileInfo(m_progressData.currentFileName,
                                        m_progressData.currentPage,
                                        m_progressData.totalPages);
        m_fileInfoLabel->setText(fileInfo);
    }

    // 更新文件进度条
    if (m_fileProgressBar && m_progressData.totalPages > 0) {
        m_fileProgressBar->setMaximum(m_progressData.totalPages);
        m_fileProgressBar->setValue(m_progressData.currentPage);
    }

    // 更新整体进度条
    if (m_overallProgressBar && m_progressData.totalFiles > 0) {
        m_overallProgressBar->setMaximum(m_progressData.totalFiles);
        m_overallProgressBar->setValue(m_progressData.completedFiles);

        QString overallInfo = formatOverallProgress(m_progressData.completedFiles,
                                                  m_progressData.totalFiles,
                                                  m_progressData.operation);
        m_overallProgressBar->setFormat(overallInfo);
    }

    // 更新状态标签
    if (m_statusLabel && !m_progressData.statusText.isEmpty()) {
        m_statusLabel->setText(m_progressData.statusText);
    }

    // 更新剩余时间标签
    if (m_timeRemainingLabel && m_progressData.estimatedTimeSeconds > 0) {
        QString timeText = formatTimeRemaining(m_progressData.estimatedTimeSeconds);
        m_timeRemainingLabel->setText(timeText);
    }
}

QString FileProgressDisplay::formatFileInfo(const QString& fileName, int currentPage, int totalPages)
{
    QString shortName = fileName;
    if (shortName.length() > 30) {
        shortName = shortName.left(27) + "...";
    }

    return QString("%1 (第 %2/%3 页)").arg(shortName).arg(currentPage).arg(totalPages);
}

QString FileProgressDisplay::formatOverallProgress(int completed, int total, const QString& operation)
{
    QString opText = operation.isEmpty() ? "处理" : operation;
    return QString("%1: %2/%3").arg(opText).arg(completed).arg(total);
}

QString FileProgressDisplay::formatTimeRemaining(int seconds)
{
    if (seconds < 60) {
        return QString("剩余 %1 秒").arg(seconds);
    } else if (seconds < 3600) {
        int minutes = seconds / 60;
        int remainingSeconds = seconds % 60;
        return QString("剩余 %1 分 %2 秒").arg(minutes).arg(remainingSeconds);
    } else {
        int hours = seconds / 3600;
        int minutes = (seconds % 3600) / 60;
        return QString("剩余 %1 小时 %2 分").arg(hours).arg(minutes);
    }
}

void FileProgressDisplay::onCancelClicked()
{
    emit cancelRequested();
}

void FileProgressDisplay::onDetailsClicked()
{
    emit detailsRequested();
}

void FileProgressDisplay::onMinimizeClicked()
{
    emit minimizeRequested();
}